package com.zhl.study.controller;

import com.zhl.study.annotation.Prevent;
import com.zhl.study.service.TokenUtilService;
import com.zhl.study.base.ResponseFactory;
import com.zhl.study.base.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @description TODO
 * @Author: z156940l@outlook.com
 * @className TokenController
 * @Date: 2023/4/26 22:05
 */
@RestController
@RequestMapping("api/")
@Api(value = "接口幂等性", tags = "接口幂等性")
public class TokenController {

    @Autowired
    private TokenUtilService tokenService;

    /**
     * 获取 Token 接口
     *
     * @return Token 串
     */
    @GetMapping("/token")
    @ApiOperation(httpMethod = "GET", value = "获取token")
    public Result<String> getToken() {
        String userInfo = "mydlq";
        // 获取 Token 字符串，并返回
        return ResponseFactory.ok(tokenService.generateToken(userInfo));
    }


    /**
     * 接口幂等性测试接口
     *
     * @param token 幂等 Token 串
     * @return 执行结果
     */
    @PostMapping("/test")
    @ApiOperation(httpMethod = "POST", value = "测试多次点击")
    public Result<String> test(@RequestHeader(value = "token") String token) {
        // 获取用户信息（这里使用模拟数据）
        String userInfo = "mydlq";
        // 根据 Token 和与用户相关的信息到 Redis 验证是否存在对应的信息
        boolean result = tokenService.validToken(token, userInfo);
        // 根据验证结果响应不同信息
        return ResponseFactory.ok(result ? "正常调用" : "重复调用");
    }

    @GetMapping("/prevent/{id}")
    @ApiOperation(httpMethod = "GET", value = "接口防止重复刷新")
    @Prevent(message = "10秒内不允许重复调多次", value = "10")
    public Result<Void> prevent(@PathVariable("id") String id) {
        return ResponseFactory.ok();
    }
}
